package com.xinyiweidai.xinyiweidai.module.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lan.mylibrary.okhttp.L;
import com.lan.mylibrary.okhttp.OkHttpUtils;
import com.lan.mylibrary.okhttp.callback.StringCallback;
import com.lan.mylibrary.ui.MyTextView;
import com.lan.mylibrary.ui.MyToast;
import com.lan.mylibrary.util.AppUtil;
import com.xinyiweidai.xinyiweidai.Constants;
import com.xinyiweidai.xinyiweidai.R;
import com.xinyiweidai.xinyiweidai.base.BaseFragment;
import com.xinyiweidai.xinyiweidai.bean.LoanMoneyBean;
import com.xinyiweidai.xinyiweidai.bean.LoginBean;
import com.xinyiweidai.xinyiweidai.module.bind.BindingActivity;
import com.xinyiweidai.xinyiweidai.module.login.LoginActivity;
import com.xinyiweidai.xinyiweidai.util.Api;
import com.xinyiweidai.xinyiweidai.util.SpUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Request;

/**
 * classname: $CLASS_NAME$
 * Data：2018/9/20-10:46
 * Author: lanxiong
 * Description:
 */

public class HomeFragment extends BaseFragment {


    private AlertDialog moneyDialog;
    private TextView tv_pay_time,tv_money,tv_days;
    private LinearLayout ll_hint_01;
    private TextView tv_hint_2;
    private Button btn_get_money;


    public static HomeFragment newInstance() {
        return new HomeFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }


    @SuppressLint("SetTextI18n")
    @Override
    protected void initView(View view) {
        tv_days = (TextView) view.findViewById(R.id.tv_days);
        tv_money = (TextView) view.findViewById(R.id.tv_money);
        tv_hint_2 = (TextView) view.findViewById(R.id.tv_hint_2);
        tv_pay_time = (TextView) view.findViewById(R.id.tv_pay_time);
        btn_get_money = (Button) view.findViewById(R.id.btn_get_money);
        ll_hint_01 = (LinearLayout) view.findViewById(R.id.ll_hint_01);

        tv_pay_time.setText(AppUtil.getDelayTime(6) + "\n还款日期");
        checkStatus();
    }


    private void checkStatus() {
        if (!Constants.isLogin||SpUtil.getInstance().getUserInfo().getZhuangtai().equals("0")) {
            btn_get_money.setText("立即提现");
            btn_get_money.setEnabled(true);
            ll_hint_01.setVisibility(View.VISIBLE);
            tv_hint_2.setVisibility(View.GONE);
        }  else if (SpUtil.getInstance().getUserInfo().getZhuangtai().equals("1")) {
            btn_get_money.setText("订单审核中...");
            btn_get_money.setEnabled(false);
            ll_hint_01.setVisibility(View.VISIBLE);
            tv_hint_2.setVisibility(View.GONE);
        } else {
            btn_get_money.setText("订单进行中...");
            btn_get_money.setEnabled(false);
            ll_hint_01.setVisibility(View.GONE);
            tv_hint_2.setVisibility(View.VISIBLE);
        }
    }



    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (SpUtil.getInstance().getUserInfo().getToken().equals("000000")){
            checkStatus();
        }else{
            refreshLogin();
        }

    }


//
//    //退出登陆
//    private void loginOut() {
//        //showLoading("正在退出");
//        new Handler().postDelayed(() -> {
//            SpUtil.getInstance().clearUserInfo();
//            SpUtil.getInstance().saveBoolean("isAutoLogin",false);
//            Constants.isLogin = false;
//            //dismissLoading();
//            //MyToast.showSuccess(getActivity(), "退出成功");
//        }, 1000);
//    }

    //刷新状态
    private void refreshLogin() {
        Map<String,String> map=new HashMap<>();
        map.put("token",SpUtil.getInstance().getUserInfo().getToken());
        OkHttpUtils
                .get()
                .url(Api.refresh)
                .params(map)
                .build()
                .execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {}

            @Override
            public void onResponse(String response) {
                L.e(response);
                LoginBean bean=new Gson().fromJson(response,LoginBean.class);
                if (bean.getCode()==1){
                    SpUtil.getInstance().saveUserInfo(bean.getData().getUserinfo());
                    checkStatus();
                }
            }
        });
    }


    @Override
    protected void addClickEvent() {
        btn_get_money.setOnClickListener(view -> checkLogin());
        tv_money.setOnClickListener(view -> showMoneyDialog());
        tv_days.setOnClickListener(view -> showDaysDialog());
    }


    @SuppressLint("SetTextI18n")
    private void showDaysDialog() {
        final String[] daysArray = {"7天"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
        alertBuilder.setTitle("借款期限");
        alertBuilder.setSingleChoiceItems(daysArray, 0, (arg0, index) -> tv_days.setText("期限："+daysArray[index]));
        alertBuilder.setPositiveButton("确定", null);
        alertBuilder.setNegativeButton("取消", null);
        moneyDialog = alertBuilder.create();
        moneyDialog.show();
    }


    @SuppressLint("SetTextI18n")
    private void showMoneyDialog() {
        final String[] moneyArray = {"1500"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
        alertBuilder.setTitle("借款额度");
        alertBuilder.setSingleChoiceItems(moneyArray, 0, (arg0, index) -> tv_money.setText("额度："+moneyArray[index]));
        alertBuilder.setPositiveButton("确定",null);
        alertBuilder.setNegativeButton("取消", null);
        moneyDialog = alertBuilder.create();
        moneyDialog.show();
    }


    private void checkLogin() {
        if (!Constants.isLogin) {
            startActivityForResult(new Intent(getActivity(),LoginActivity.class),100);
        } else if (SpUtil.getInstance().getUserInfo().getAllbind().equals("1")) {
            showLoanDialog();
        } else {
            startNewActivity(BindingActivity.class);
            MyToast.showSuccess(getActivity(), "请先认证");
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==100&&resultCode==102){
            checkStatus();
        }
    }


    @SuppressLint("SetTextI18n")
    private void showLoanDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_loan, null);
        builder.setView(view)
                .setCancelable(false)
                .create();
        AlertDialog dialog = builder.show();

        MyTextView textView=dialog.findViewById(R.id.tv_loan_info);
        textView.setText("借款"+tv_money.getText().toString()+
                "\n借款"+tv_days.getText().toString()+
                "\n还款日期："+AppUtil.getDelayTime(6));

        dialog.findViewById(R.id.tv_sure).setOnClickListener(view1 -> {onLoanDialogClick();dialog.dismiss();});
        dialog.findViewById(R.id.tv_cancel).setOnClickListener(view1 -> dialog.dismiss());
    }


    public void onLoanDialogClick() {
        showLoading("正在加载");
        Map<String, String> map = new HashMap<>();
        map.put("userid", SpUtil.getInstance().getUserInfo().getUser_id());
        OkHttpUtils
                .get()
                .url(Api.loanMoney)
                .params(map)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        L.e(e.toString());
                        dismissLoading();
                        MyToast.showError(getActivity(), "网络异常");
                    }

                    @Override
                    public void onResponse(String response) {
                        L.e(response);
                        dismissLoading();
                        parseData(response);
                    }
                });
    }


    private void parseData(String response) {
        LoanMoneyBean bean = new Gson().fromJson(response, LoanMoneyBean.class);
        if (bean.getCode() == 1) {
            SpUtil.getInstance().getUserInfo().setZhuangtai("1");
            MyToast.showSuccess(getActivity(),"申请成功");
            refreshLogin();
        } else {
            MyToast.showError(getActivity(), bean.getMsg());
        }
    }
}
